<extend name="Manage/themes/default/base" />
<block name="main">
    <div class="layui-fluid">
        <div class="layui-row">
            <form class="layui-form">
                <table class="table-form">
                    <tr>
                        <td width="100" align="right" class="td-title">
                            <span class="x-red">*</span>名称：
                        </td>
                        <td>
                            <input id="name" value="{{$info['name']??''}}" class="layui-input" size="40">
                        </td>
                    </tr>

                    <tr>
                        <td width="100" align="right" class="td-title">
                            <span class="x-red">*</span>apiKey：
                        </td>
                        <td>
                            <input id="api_key" value="{{$info['api_key']??''}}" class="layui-input" size="40">
                            <span class="x-red">(纯数字,最多6位)</span>
                        </td>
                    </tr>

                    <tr>
                        <td align="right" class="td-title">
                            <span class="x-red">*</span>apiSecret:
                        </td>
                        <td>
                            <input id="secret" value="{{$info['secret']??''}}" class="layui-input" size="50">
                            <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="Pages.createApikey()">生成秘钥</button>
                            <span class="x-red">(英文字母数字组成，区分大小写)</span>
                        </td>
                    </tr>

                    <tr>
                        <td align="right" class="td-title">
                            <span class="x-red">*</span>类型:
                        </td>
                        <td>{{$info['type_name']}}</td>
                    </tr>


                    <if condition="$info['client_type'] == 2">
                        <tr>
                            <td align="right" class="td-title">
                                拥有资源:
                            </td>
                            <td valign="top">
                                <button type="button" class="layui-btn layui-btn-xs layui-btn-normal" onclick="Pages.openResourcePoper()"><i class="layui-icon">&#xe654;</i>绑定资源</button>
                                <table class="layui-table layui-form">
                                    <thead>
                                    <tr>
                                        <th width="10%" class="align-center">Id</th>
                                        <th width="30%">名称</th>
                                        <th width="20%" class="align-center">请求类型</th>
                                        <th width="25%" class="align-center">路径</th>
                                        <th class="align-center">操作</th>
                                    </tr>
                                    </thead>
                                    <tbody id="resources-list">
                                        <foreach name="$info['resources']"  key="rk" item="rv" >

                                            <tr data-id="{{$rv['id']}}">
                                                <td class="align-center">{{$rv['id']}}</td>
                                                <td>{{$rv['name']}}</td>
                                                <td class="align-center">{{$rv['request_method']}}</td>
                                                <td class="align-center">{{$rv['path']}}</td>
                                                <td class="align-center">
                                                    <a href="javascript:void(0)" onclick="Pages.delResourceItem(this)" class="layui-btn layui-btn-xs layui-btn-danger"><i class="layui-icon">&#xe640;</i>删除</a>
                                                </td>
                                            </tr>
                                        </foreach>
                                    </tbody>
                                </table>
                            </td>
                        </tr>
                    </if>
                    <tr>
                        <td></td>
                        <td class="x-red">(如果修改apiKey 或 apiSecret则使用该信息的客户端将无法使用，请谨慎修改)</td>
                    </tr>


                    <tr>
                        <td></td>
                        <td>
                            <button class="layui-btn layui-btn-danger layui-btn-lg" onclick="Pages.sureSave()" type="button">确定保存</button>
                        </td>
                    </tr>
                </table>
            </form>
        </div>
    </div>
    <script>
        var form;
        var id = parseInt({{$id??0}});

        layui.use(['form'], function(){
            form = layui.form;
        });


        var Pages = {
            canOperate:true, //能否操作
            /**
             * 生成随机秘钥
             */
            createApikey:function(){
                var randStr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j','k','l','m','n','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'];
                var len = randStr.length;
                var str = '';
                for(var i=0;i<40;i++){
                    var k = Math.floor(Math.random()*len);
                    str +=  randStr[k];
                }
                $('#secret').val(str);
            },
            openResourcePoper:function(){
                ResourcePoper.init({'operateType':'multi','url':'outapi/clients/resources'});
            },

            /**
             * 创建资源Html
             */
            createResourceHtml:function(list){
                var str = '';
                for(var i in list){
                    if($('#resources-list tr[data-id="'+list[i]['id']+'"]').length>0){
                        continue;
                    }
                    str+='<tr data-id="'+list[i]['id']+'">';
                    str+='  <td class="align-center">'+list[i]['id']+'</td>';
                    str+='  <td>'+list[i]['name']+'</td>';
                    str+='  <td class="align-center">'+list[i]['request_method']+'</td>';
                    str+='  <td class="align-center">'+list[i]['path']+'</td>';
                    str+='  <td class="align-center"><a href="javascript:void(0)" onclick="Pages.delResourceItem(this)" class="layui-btn layui-btn-xs layui-btn-danger"><i class="layui-icon">&#xe640;</i>删除</a></td>';
                    str+='</tr>';
                }
                $('#resources-list').append(str);
            },
            delResourceItem:function(obj){
                $(obj).closest('tr').remove();
            },
            sureSave:function(){
                if(!Pages.canOperate){
                    return false;
                }
                var params = {};
                params.name = $('#name').val();
                params.secret = $('#secret').val();
                params.id = id;
                params.api_key = $('#api_key').val();
                var resourceIds = new Array();
                var resourcesObj = $('#resources-list tr');
                for(var i=0; i<resourcesObj.length;i++){
                    resourceIds.push(resourcesObj.eq(i).attr('data-id'));
                }
                params.resources_ids = resourceIds.join(',');

                var loading = VK.load();
                var method = id >0 ? 'PUT':'POST';
                var url = id>0 ? VK.U('outapi/clients/'+id):VK.U('outapi/clients');
                Pages.canOperate = false;
                VK.QAjax(url,method,params,function (res) {
                    VK.closeLoad(loading);
                    if (res.status != 200){
                        Pages.canOperate = true;
                        VK.error(res.msg);
                        return false;
                    }
                    VK.success(res.msg);
                    setTimeout(function(){
                        VK.nofifyParentPage("reloadList");
                        VK.closeNowPage();
                    },1500);
                },function (res) {
                    VK.closeLoad(loading);
                    Pages.canOperate = true;
                    VK.error('系统出错稍后再试');
                });
            }
        }

        /**
         * 资源选择弹窗
         */
        var ResourcePoper = {
            operateType:'radio',
            isFirst:true,
            searchParam:{ //搜索字段
            },
            poperHandel:'',
            loadingHandel:'',
            laypage:'',
            url:'outapis/resources',
            init:function(options){
                layui.use('laypage', function(){
                    ResourcePoper.laypage = layui.laypage;
                });
                ResourcePoper.isFirst = true;
                ResourcePoper.searchParam = {};
                if('operateType' in options){
                    ResourcePoper.operateType = options.operateType;
                }
                if('url' in options){
                    ResourcePoper.url = options.url;
                }
                var str =  '<div class="poper-window">';
                str+='<div class="poper-search-block">';
                str+='   <span class="item"><input type="text" size="30" id="poper-resouces-name"/></span>';
                str+='   <span class="item"><button class="layui-btn" lay-submit="" lay-filter="sreach" type="button" onclick="ResourcePoper.searchList()"><i class="layui-icon">&#xe615;</i></button></span>';
                str+='<div style="clear:both;"></div>';
                str+='</div>';
                str += '<table class="layui-table" style="width:100%; margin-top:0px;">';
                str += '    <thead>';
                str += '        <tr>';
                str += '            <th width="8%">Id</th>';
                str += '            <th width="24%">名称</th>';
                str += '            <th width="20%">请求方式</th>';
                str += '            <th width="30%">路径</th>';
                str += '            <th>';
                if(ResourcePoper.operateType == 'multi'){
                    str +='             <input type="checkbox" onClick="ResourcePoper.chooseAll(this)">';
                }
                str += '            操作</th>';
                str += '        </tr>';
                str += '    </thead>';
                str += '    <tbody id="poper-resouces-list"></tbody>';
                str +='     <tr>';
                str +='         <td colspan="2">';
                if(ResourcePoper.operateType == 'multi'){
                    str +='             <a href="javascript:void(0);" class="layui-btn layui-btn-xs layui-btn-danger" onclick="ResourcePoper.selectMulti()""><i class="layui-icon">&#xe605;</i>确定选择</a>';
                }
                str +='         </td>';
                str +='         <td colspan="3" id="poper-resouces-pager"></td>';
                str +='     </tr>';
                str += '</table>';
                str += '</div>';
                var w = $(window).outerWidth()*0.9;
                var h = $(window).outerHeight()*0.9;
                ResourcePoper.poperHandel=layer.open({
                    type: 1,
                    title:'资源列表',
                    content: str,
                    area: [w+'px', h+'px']
                });
                ResourcePoper.getDataList(1);
            },
            getDataList:function(page)
            {
                ResourcePoper.searchParam.page = page;
                ResourcePoper.loadingHandel = layer.load();
                VK.QAjax(VK.U(ResourcePoper.url),'get',ResourcePoper.searchParam,function(res){
                    layer.close(ResourcePoper.loadingHandel);
                    var data = res.data;
                    ResourcePoper.rendListHtml(data.data);
                    ResourcePoper.isFirst = false;
                    ResourcePoper.rendPager(data.total,data.per_page,data.current_page);
                });
            },
            rendListHtml:function(list){
                var str = '';
                for (var i = 0; i < list.length; i++) {
                    str+='<tr data-id="'+list[i]['id']+'" name="'+list[i]['name']+'" request_method="'+list[i]['request_method']+'" path="'+list[i]['path']+'">';
                    str+=' <td>'+list[i]['id']+'</td>';
                    str+=' <td>'+list[i]['name']+'</td>';
                    str+=' <td>'+list[i]['request_method']+'</td>';
                    str+=' <td>'+list[i]['path']+'</td>';
                    str+=' <td>';
                    if(ResourcePoper.operateType == 'radio'){
                        str+='<a class="layui-btn layui-btn-xs" onclick="ResourcePoper.selectItem('+list[i]['id']+')">选择</a>';
                    }else if(ResourcePoper.operateType == 'multi'){
                        str+='<input type="checkbox">';
                    }
                    str+=' </td>';
                    str+='</tr>';
                }
                $('#poper-resouces-list').html(str);
            },
            /**
             * 渲染分页条
             */
            rendPager:function(total,per_page,current_page){
                ResourcePoper.laypage.render({
                    elem : 'poper-resouces-pager',  //id
                    count : total,  //总数据
                    limit : per_page,//一页多少数据
                    curr : current_page,//当前页
                    theme : '#015293',        //颜色设置
                    layout : ['count', 'prev', 'page', 'next',  'skip'],     //分页的配置
                    jump:function(obj,first) {
                        ResourcePoper.searchParam.limit = obj.limit;
                        //首次不执行
                        if(!first){
                            ResourcePoper.getDataList(obj.curr);
                        }
                    }
                });
            },
            /**
             * 搜索
             */
            searchList:function(){
                ResourcePoper.searchParam.name = $('#poper-resouces-name').val();
                ResourcePoper.getDataList(1);
            },
            /**
             * 获取选择的数据详细
             */
            getItemData:function(id){
                var obj =  $('#poper-resouces-list tr[data-id="'+id+'"]');
                return {
                    'id':id,
                    'name':obj.attr('name'),
                    'request_method':obj.attr('request_method'),
                    'path':obj.attr('path')
                };
            },
            getMultiSelectData:function(){
                var obj = $('#poper-resouces-list tr');
                var list = {};
                var index = 0;
                for (var i = 0; i < obj.length; i++) {
                    if(obj.eq(i).find('input[type="checkbox"]').prop('checked')){
                        list[index] ={
                            'id':obj.eq(i).attr('data-id'),
                            'name':obj.eq(i).attr('name'),
                            'path':obj.eq(i).attr('path'),
                            'request_method':obj.eq(i).attr('request_method')
                        }
                        index++;
                    }
                }
                return list;
            },
            chooseAll:function(obj){
                var isChecked = $(obj).prop('checked')?true:false;
                var targetObj = $('#poper-resouces-list tr');
                for (var i = 0; i < targetObj.length; i++) {
                    targetObj.eq(i).find('input[type="checkbox"]').prop('checked',isChecked);
                }
            },
            /**
             * 关闭页面
             */
            closePoper:function(){
                layer.close(ResourcePoper.poperHandel);
            }
        }
        ResourcePoper.selectItem = function(id){
            var data = ResourcePoper.getItemData(id);
            var list = {
                'id':id,
                'name':data.name,
                'path':data.path,
                'request_method':data.request_method
            };
            Pages.createResourceHtml(list);
            ResourcePoper.closePoper();
        }
        ResourcePoper.selectMulti = function(){
            var list = ResourcePoper.getMultiSelectData();
            if(JSON.stringify(list) == '{}'){
                VK.error('请选择');
                return false;
            }
            Pages.createResourceHtml(list);
            ResourcePoper.closePoper();
        }

    </script>
</block>